var AjaxCrud = QualityCheck.AjaxCRUD;
var serverUrl = QualityCheck.GPUD.ServiceConfig;
var currentPage = 1;
//var pageSize = 10;
var map = null;
var toolbar = null;
var scale = null;
var totalPage;
var lineMarker = {};//轨迹线对象
var pointMarker = {};//轨迹点对象
var historyData = null;
var latlngsli = [];
$(function(){
	var usercode = $("#user-name",parent.parent.document).attr("code");
	var userkey = $("#user-name",parent.parent.document).attr("key");
	var usertype = $("#user-name",parent.parent.document).attr("usertype");
	keyCheck(usercode,usertype,userkey,function(){
		initPages();
		window.onresize = function () {
			initPages();
		};
		initTime();
		pageBtns();
		initMap();
		initClass();
	});
});
function initTime(){
	var date = new Date();
	var newDate = getFormatDate(date,"yyyy-MM-dd hh:mm");
	var startTime = getFormatDate(new Date(date.getTime()),"yyyy-MM-dd ");
	$("#startTime").val(startTime+"00:00");
	$("#endTime").val(newDate);
}
function initMap(){
	map = new AMap.Map("map",{
		level:15,//设置地图缩放级别
	});
	map.plugin(["AMap.ToolBar","AMap.OverView","AMap.Scale"],function(){ 
		toolbar = new AMap.ToolBar();
		toolbar.autoPosition=false; //加载工具条 
		map.addControl(toolbar);  	
		scale = new AMap.Scale(); //加载比例尺
		map.addControl(scale);
	});
	map.setDefaultCursor("url(http://developer.amap.com/wp-content/uploads/2014/06/closedhand.cur),pointer");
	$(".amap-logo").hide();
	$(".amap-copyright").hide();
	$(".amap-container").css("position","absolute");
	getNowCity();
}
function getNowCity(){
	  //加载城市查询插件
		AMap.service(["AMap.CitySearch"], function() {
		    //实例化城市查询类
		    var citysearch = new AMap.CitySearch();
		    //自动获取用户IP，返回当前城市
		    citysearch.getLocalCity(function(status, result) {
		        if (status === 'complete' && result.info === 'OK') {
		            if (result && result.city && result.bounds) {
		                var citybounds = result.bounds;
		                //地图显示当前城市
		                map.panTo(new AMap.LngLat(citybounds.getCenter().lng,citybounds.getCenter().lat));
		            }
		        }
		    });
		});
}

function initClass(){
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var userRoles = $("#user-name",parent.parent.document).attr("rolecodes");
	var data = {
			cmd:"getDataRole",
			model:"license",
			userKey:userKey,
			data:{
				rolecode:userRoles
			},
			remark:"",
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		var typeOpt = "";
		var gradeOpt = "";
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var data = res.data;
			for(var i = 0; i < data.length; i++){
				var name = "";
				if(data[i].type == "0"){
					name = "幼儿园";
				}else if(data[i].type == "1"){
					name = "小学";
				}else if(data[i].type == "2"){
					name = "中学";
				}else if(data[i].type == "3"){
					name = "高中";
				}
				typeOpt += "<option value='"+data[i].type+"'>"+name+"</option>";
			}
			$("#type-position").html(typeOpt);
			
			var gradeData = data[0].data;
			for(var i = 0; i < gradeData.length; i++){
				gradeOpt += "<option value='"+gradeData[i].grade+"' classcodes='"+gradeData[i].classcode+"' classes='"+gradeData[i].classes+"'>"+gradeData[i].grade+"年级</option>";
			}
			$("#grade-position").html(gradeOpt);
			
			var classes = $("#grade-position option:selected").attr("classes").split(",");
			var classcodes = $("#grade-position option:selected").attr("classcodes").split(",");
			var classOpt = "";
			for(var j = 0; j < classes.length; j++){
				classOpt += "<option value='"+classcodes[j]+"' classes='"+classes[j]+"'>"+classes[j]+"班</option>";
			}
			$("#class-position").html(classOpt);
			
			$("#type-position").unbind("change");
			$("#type-position").change(function(){
				var gradeData = null;
				var type = $("#type-position option:selected").val();
				var gradeOpt = "";
				if(type != ""){
					for(var i = 0; i < data.length; i++){
						if(data[i].type == type){
							gradeData = data[i].data;
						}
					}
					for(var i = 0; i < gradeData.length; i++){
						gradeOpt += "<option value='"+gradeData[i].grade+"' classcodes='"+gradeData[i].classcode+"' classes='"+gradeData[i].classes+"'>"+gradeData[i].grade+"年级</option>";
					}
				}
				$("#grade-position").html(gradeOpt);
				
				var classes = $("#grade-position option:selected").attr("classes").split(",");
				var classcodes = $("#grade-position option:selected").attr("classcodes").split(",");
				var classOpt = "";
				for(var j = 0; j < classes.length; j++){
					classOpt += "<option value='"+classcodes[j]+"' classes='"+classes[j]+"'>"+classes[j]+"班</option>";
				}
				$("#class-position").html(classOpt);
				initStudentTable(1);
			});
			
			$("#grade-position").unbind("change");
			$("#grade-position").change(function(){
				var classes = $("#grade-position option:selected").attr("classes").split(",");
				var classcodes = $("#grade-position option:selected").attr("classcodes").split(",");
				var classOpt = "";
				for(var j = 0; j < classes.length; j++){
					if(classcodes[j] == "" && classes[j] == ""){
						classOpt += "<option value='' classes=''>班级</option>";
					}else{
						classOpt += "<option value='"+classcodes[j]+"' classes='"+classes[j]+"'>"+classes[j]+"班</option>";
					}
				}
				$("#class-position").html(classOpt);
				initStudentTable(1);
			});
			
			$("#class-position").unbind("change");
			$("#class-position").change(function(){
				initStudentTable(1);
			});
		}else{
			
		}
		initStudentTable(1);
	},null,null);
}
function initStudentTable(currentpage){
	processBegin("数据加载中······");
	currentPage = currentpage;
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var userRoles = $("#user-name",parent.parent.document).attr("rolecodes");
	var schoolcode = $("#user-name",parent.parent.document).attr("schoolcode");
	var classcode = $("#class-position option:selected").val();
	var type = $("#type-position option:selected").val();
	var obj = {};
	obj.currentpage = currentpage;
//	obj.pagesize = 10;
	obj.schoolcode = schoolcode;
	obj.rolecode = userRoles;
	obj.type = type;
	if(classcode != ""){
		obj.classcode = classcode;
	}
	var data = {
			cmd:"getAllStudentsByPage",
			model:"student",
			userKey:userKey,
			data:obj,
			remark:"",
			
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		var content = "";
		if(res.result == 1 && res.data != undefined && res.data != ""){
			var data = res.data.data;
//			var total = res.data.total;
//			totalPage = Math.ceil(total/pageSize);
//			$("#total-page").text(totalPage);
//			$("#now-page").text(currentpage);
			if(data.length > 0){
				for(var i = 0; i < data.length; i++){
					for(var key in data[i]){
						if(data[i][key] == null || data[i][key] == undefined){
							data[i][key] = "";
						}
					}
					content += "<div class=\"data-trs-show\" studentcode = \""+data[i].studentcode+"\">" +
									"<div class=\"pdata-name\" title='"+data[i].name+"'>"+substr(data[i].name,5)+"</div>" +
									"<div class=\"pdata-img\">" +
										"<img src=\"../../../../../../"+ServiceName+data[i].headimg+"\" width=\"100%\" height=\"100%\"/>" +
									"</div>" +
									"<div class=\"pdata-class\">"+data[i].grade + "年级" + data[i].clazz + "班</div>" +
									"<div class=\"pdata-add\" title=\""+data[i].adress+"\">" + substr(data[i].adress,9) + "</div>" +
								"</div>";
				}
				
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
				
				$(".data-trs-show").click(function(){
					var studentcode = $(this).attr("studentcode");
					getStudentHistory(studentcode);
				});
				
			}else{
				content += "<div class='no-res-show'>未查询到相关数据！</div>";
				$(".left-datas-show").empty();
				$(".left-datas-show").append(content);
			}
			processEnd("加载成功");
		}else{
			content += "<div class='no-res-show'>查询服务出错了！</div>";
			$(".left-datas-show").empty();
			$(".left-datas-show").append(content);
			processError("加载失败");
		}
	},null,null);											
}
function getStudentHistory(studentcode){
	totaltime = 0;
	now = 0;
	per = 0;
	map.clearInfoWindow();
	parseMove();
	nowFlagPo(now,per);
	$(".history-audio-btns-play").show();
	$(".history-audio-btns-parse").hide();
	var starttime = strToDate($("#startTime").val()+":00");
	var endtime = strToDate($("#endTime").val()+":59");
	var userKey = $("#user-name",parent.parent.document).attr("key");
	var usertype = $("#user-name",parent.parent.document).attr("usertype");
	var data = {
			cmd:"getHistoryPositionByStudentCode",
			model:"position",
			userKey:userKey,
			data:{
				startTime:starttime,
				endTime:endtime,
				studentcode:studentcode,
				usertype: usertype,
			},
			remark:""
			
	};
	AjaxCrud.get(serverUrl.ServerLoginUrl,data,function(res){
		if(res.result == 1 && res.data != undefined && res.data != ""){
			if(res.data[0].msg == "没有权限查询"){
				processError("查询时间请选择8点至18点，周六日不可查询");
			}else{
				processEnd("查询成功，点击播放回顾");
				historyData = res;
				if(lineMarker["line"]){
					lineMarker["line"].setMap(null);
				}
				for(var key in pointMarker){
					if(pointMarker[key]){
						pointMarker[key].setMap(null);
					}
				}
				var showObj;
				per = computePerFlag(res.data.length);
				for(var i = 0; i < res.data.length; i++){
					var lonlat = res.data[i].lonLat;
					if(lonlat != null && lonlat != ""){
						var list = lonlat.split(",");
						var y = list[0];
						var x = list[1];
						
						showObj = {};
						showObj["电量"] = "<img src='../../../../img/position/power_"+ res.data[i].power +".png' style='padding-top:5px;'/>";
						showObj["数据时间"] = res.data[i].time;
						showObj["手机"] = res.data[i].cellphone;
						if(res.data[i].address != null){
							showObj["当前位置"] = res.data[i].address;
						}else{
							showObj["当前位置"] = "暂时不能定位到准确地点";
						}
						var imgUrl = "";
						if(res.data[i].type == 0 || res.data[i].type == "0"){
							imgUrl = '../../../../img/position/lishi-lx.png';
							showObj["定位方式"] = "离线";
						}else if(res.data[i].type == 1 || res.data[i].type == "1"){
							imgUrl = '../../../../img/position/lishi-bd.png';
							showObj["定位方式"] = "北斗定位";
						}else if(res.data[i].type == 2 || res.data[i].type == "2"){
							imgUrl = '../../../../img/position/lishi-sn.png';
							showObj["定位方式"] = "蓝牙定位";
						}else if(res.data[i].type == 3 || res.data[i].type == "3"){
							imgUrl = '../../../../img/position/lishi-jz.png';
							showObj["定位方式"] = "基站定位";
						}
						var icon = new AMap.Icon({
							size:new AMap.Size(16,16),//图标大小
							image:imgUrl,//大图地址
							imageSize:new AMap.Size(16,16)
						});
						
						addMarker(x,y,icon,showObj,"history"+i);
					}
				}
				var lonlat = res.data[0].lonLat;
				if(lonlat != "" && lonlat != null){
					var list = lonlat.split(",");
					var ys = list[0];
					var xs = list[1];
					map.panTo(new AMap.LngLat(ys,xs));
				}
	        	latlngsli = [];
				for(var i = 0; i < res.data.length; i ++){
					var lonlat = res.data[i].lonLat;
					if(lonlat != null && lonlat != ""){
						var list = lonlat.split(",");
						var x = list[0];
						var y = list[1];
						latlngsli.push([x*1,y*1]);
					}
				}
				if(latlngsli.length > 1){
//					addLine("history",latlngsli);
				}
			}
		}else{
			processError("未查询到历史足迹");
			if(lineMarker["history"]){
				lineMarker["history"].setMap(null);
			}
			for(var key in pointMarker){
				if(pointMarker[key]){
					pointMarker[key].setMap(null);
				}
			}
		}
	},null,null);
}
function pageBtns(){
	$("#last-page").click(function(){
		if(currentPage > 1){
			currentPage --;
			initStudentTable(currentPage);
		}else{
			return false;
		}
	});
	$("#next-page").click(function(){
		if(currentPage < totalPage){
			currentPage ++;
			initStudentTable(currentPage);
		}else{
			return false;
		}
	});
	$(".history-audio-btns-back").click(function(){
		var res = historyData;
		now = now - 3;
		if(now < 0){
			now = 0;
		}
		for(var key in pointMarker){
			if(pointMarker[key]){
				pointMarker[key].setMap(null);
			}
		}
		var showObj;
		per = computePerFlag(res.data.length);
		for(var i = 0; i < now; i++){
			var lonlat = res.data[i].lonLat;
			if(lonlat != null && lonlat != ""){
				var list = lonlat.split(",");
				var y = list[0];
				var x = list[1];
				
				showObj = {};
				showObj["电量"] = "<img src='../../../../img/position/power_"+ res.data[i].power +".png' style='padding-top:5px;'/>";
				showObj["数据时间"] = res.data[i].time;
				showObj["手机"] = res.data[i].cellphone;
				if(res.data[i].address != null){
					showObj["当前位置"] = res.data[i].address;
				}else{
					showObj["当前位置"] = "暂时不能定位到准确地点";
				}
				var imgUrl = "";
				if(res.data[i].type == 0 || res.data[i].type == "0"){
					imgUrl = '../../../../img/position/lishi-lx.png';
					showObj["定位方式"] = "离线";
				}else if(res.data[i].type == 1 || res.data[i].type == "1"){
					imgUrl = '../../../../img/position/lishi-bd.png';
					showObj["定位方式"] = "北斗定位";
				}else if(res.data[i].type == 2 || res.data[i].type == "2"){
					imgUrl = '../../../../img/position/lishi-sn.png';
					showObj["定位方式"] = "蓝牙定位";
				}else if(res.data[i].type == 3 || res.data[i].type == "3"){
					imgUrl = '../../../../img/position/lishi-jz.png';
					showObj["定位方式"] = "基站定位";
				}
				var icon = new AMap.Icon({
					size:new AMap.Size(16,16),//图标大小
					image:imgUrl,//大图地址
					imageSize:new AMap.Size(16,16)
				});
				
				addMarker(x,y,icon,showObj,"history"+i);
			}
		}
	});
	$(".history-audio-btns-play").click(function(){
		startMove();
		$(".history-audio-btns-play").hide();
		$(".history-audio-btns-parse").show();
	});
	$(".history-audio-btns-parse").click(function(){
		parseMove();
		$(".history-audio-btns-play").show();
		$(".history-audio-btns-parse").hide();
	});
	$(".history-audio-btns-forward").click(function(){
		var res = historyData;
		now = now + 3;
		if(now >= totaltime){
			now = totaltime;
		}
		for(var key in pointMarker){
			if(pointMarker[key]){
				pointMarker[key].setMap(null);
			}
		}
		var showObj;
		per = computePerFlag(res.data.length);
		for(var i = 0; i < now; i++){
			var lonlat = res.data[i].lonLat;
			if(lonlat != null && lonlat != ""){
				var list = lonlat.split(",");
				var y = list[0];
				var x = list[1];
				
				showObj = {};
				showObj["电量"] = "<img src='../../../../img/position/power_"+ res.data[i].power +".png' style='padding-top:5px;'/>";
				showObj["数据时间"] = res.data[i].time;
				showObj["手机"] = res.data[i].cellphone;
				if(res.data[i].address != null){
					showObj["当前位置"] = res.data[i].address;
				}else{
					showObj["当前位置"] = "暂时不能定位到准确地点";
				}
				var imgUrl = "";
				if(res.data[i].type == 0 || res.data[i].type == "0"){
					imgUrl = '../../../../img/position/lishi-lx.png';
					showObj["定位方式"] = "离线";
				}else if(res.data[i].type == 1 || res.data[i].type == "1"){
					imgUrl = '../../../../img/position/lishi-bd.png';
					showObj["定位方式"] = "北斗定位";
				}else if(res.data[i].type == 2 || res.data[i].type == "2"){
					imgUrl = '../../../../img/position/lishi-sn.png';
					showObj["定位方式"] = "蓝牙定位";
				}else if(res.data[i].type == 3 || res.data[i].type == "3"){
					imgUrl = '../../../../img/position/lishi-jz.png';
					showObj["定位方式"] = "基站定位";
				}
				var icon = new AMap.Icon({
					size:new AMap.Size(16,16),//图标大小
					image:imgUrl,//大图地址
					imageSize:new AMap.Size(16,16)
				});
				
				addMarker(x,y,icon,showObj,"history"+i);
			}
		}
	});
//	$("#startTime").unbind("change");
//	$("#startTime").change(function(){
//		var endHour = $("#endTime").val().substring(11,16);
//		var endDate = strToDate($("#startTime").val()+":00") + 1000*60*60*24;
//		$("#endTime").val(getFormatDate(new Date(endDate),"yyyy-MM-dd ")+endHour);
//	});
}
function changeTime(){
	var endHour = $("#endTime").val().substring(11,16);
	var endDate = strToDate($("#startTime").val()+":00");
	$("#endTime").val(getFormatDate(new Date(endDate),"yyyy-MM-dd ")+endHour);
}
//添加线方法并注册点的点击事件
function addLine(name,latlngs){
	if(lineMarker[name]){
		lineMarker[name].setMap(null);
	}
	lineMarker[name] = new AMap.Polyline({
        path: latlngs,          //设置线覆盖物路径
        strokeColor: "red", //线颜色
        strokeOpacity: 1,       //线透明度
        strokeWeight: 3,        //线宽
        strokeStyle: "dashed",   //线样式
        strokeDasharray: [10, 10] //补充线样式
	});
	lineMarker[name].setMap(map);
}
//添加点方法并注册线点击事件
function addMarker(x,y,icon,obj,name){
	if(pointMarker[name]){
		map.remove(pointMarker[name]);
//		pointMarker[name].setMap(null);
	}
	pointMarker[name] = new AMap.Marker({
		id:name,
		position:new AMap.LngLat(y,x),
		icon:icon, //marker图标
		offset:{x:-8,y:-8} //相对于基点的位置
	});
	pointMarker[name].setMap(map);
	    clickLayer(pointMarker[name],function(){
	    	var content = "<table>";
	    for(key in obj){
	    	if(key == "数据时间"){
	    		if(obj[key].toString().indexOf("-") < 0){
	    			obj[key] = getSmpFormatDateByLong(parseInt(obj[key])*1000,true);
	    		}
	    	}
	        content += "<tr><td style='text-align: right;font-weight:700;width:30%;'>"+key+"：</td><td>"+obj[key]+"</td></tr>";
	    }
	    content += "</table>";
	    map.clearInfoWindow();
	    var inforWindow = new AMap.InfoWindow({
			offset:new AMap.Pixel(0,0),
			content:content
		});
	    inforWindow.open(map,pointMarker[name].getPosition());
	    });
}
function clickLayer(layer,method){
	AMap.event.addListener(layer, "click", method);
}
function substr(str,len){
	if(str != undefined){
		if(str.length > len){
			str = str.substring(0,len-2)+"...";
			return str;
		}else{
			return str;
		}
	}else{
		return "";
	}
}
function computePerFlag(len){
	var totalL = $(".history-audio-time-flag").width();
	var perFlag = totalL/len;
	totaltime = len;
	return perFlag;
}
function nowFlagPo(index,per){
	$(".history-audio-time-btn").animate({"left":index*per+"px"});
}
var timer = null;
var now = 0;
var totaltime = 0;
var per = 0;
function startMove(){
	if(now == 0){
		for(var key in pointMarker){
			if(pointMarker[key]){
				pointMarker[key].setMap(null);
			}
		}
	}
	timer = window.setInterval(function(){
		if(now >= totaltime){
			window.clearInterval(timer);
			now = 0;
			nowFlagPo(now,per);
			$(".history-audio-btns-play").show();
			$(".history-audio-btns-parse").hide();
			latlngsli = [];
		}else{
			var res = historyData;
			var lonlat = res.data[now].lonLat;
			var list = lonlat.split(",");
			var y = list[0];
			var x = list[1];
			
			showObj = {};
			showObj["电量"] = "<img src='../../../../img/position/power_"+ res.data[now].power +".png' style='padding-top:5px;'/>";
			showObj["数据时间"] = res.data[now].time;
			showObj["手机"] = res.data[now].cellphone;
			if(res.data[now].address != null){
				showObj["当前位置"] = res.data[now].address;
			}else{
				showObj["当前位置"] = "暂时不能定位到准确地点";
			}
			var imgUrl = "";
			if(res.data[now].type == 0 || res.data[now].type == "0"){
				imgUrl = '../../../../img/position/lishi-lx.png';
				showObj["定位方式"] = "离线";
			}else if(res.data[now].type == 1 || res.data[now].type == "1"){
				imgUrl = '../../../../img/position/lishi-bd.png';
				showObj["定位方式"] = "北斗定位";
			}else if(res.data[now].type == 2 || res.data[now].type == "2"){
				imgUrl = '../../../../img/position/lishi-sn.png';
				showObj["定位方式"] = "蓝牙定位";
			}else if(res.data[now].type == 3 || res.data[now].type == "3"){
				imgUrl = '../../../../img/position/lishi-jz.png';
				showObj["定位方式"] = "基站定位";
			}
			var icon = new AMap.Icon({
				size:new AMap.Size(16,16),//图标大小
				image:imgUrl,//大图地址
				imageSize:new AMap.Size(16,16)
			});
			
			addMarker(x,y,icon,showObj,"zuji"+now);
			
			map.panTo(new AMap.LngLat(y,x));
			
			now ++;
			nowFlagPo(now,per);
		}
	}, 1000);
}
function parseMove(){
	window.clearInterval(timer);
}

function getEtime(){
	var stime = $("#startTime").val().split(" ")[0];
	var date = stime + " 23:59";
	return date;
}

function initPages(){
	var bodyRW = $("#aposition-body",parent.document).width() - $(".left-data-show").width();
	$("#map").width(bodyRW);
	
	$(".history-audio").width(bodyRW);
	
	var flagW = $(".history-audio").width() - 221;
	$(".history-audio-time").width(flagW);
	
	var leftDH = $(".left-data-show").height() - $(".history-search-btn").height() - $(".left-search-data").height() - $(".left-datas-page").height() - 15;
	$(".left-datas-show").height(leftDH);
}